import { FC, useMemo, useContext, useRef, useEffect, useState } from 'react';
import { InbizIcon, multilingualFormat } from '@inbiz/utils';
import { RenderSimple } from '@inbiz/render';
import { InBizTableCtx, TableCtx } from '../../context';
import cs from 'classnames';
import { onFieldValidateEnd } from '@formily/core';
import {getMessage} from '@inbiz/react'


const EditCellComponent: FC<any> = ({
  dataIndex,
  children,
  tdClickHandle,
  getPageRef,
  inlineEdit,
  changeBeforeForm,
  schema,
  beforeForm,
  inlineEditIndex,
  rowIndex,
  form,
  changeEditCell,
  primaryKey,
  onInit,
  editPage,
  emit,
  readOnly,
  eventsRef,
  viewMode,
  ...resetProps
}) => {
  const { inbiz } = useContext(InBizTableCtx);
  const { dispatch } = useContext(TableCtx);
  const formRef = useRef<any>();
  const tdRef = useRef<HTMLElement>(null);
  const notRenderRef = useRef<boolean>(false);
  const _id = resetProps.record?.[primaryKey];
  var current = schema.keysMap[dataIndex];
  var properties = current ? schema.schema.properties?.[current] : undefined;
  const [isError, $isError] = useState(false);
  // const defaultValue=
  const isTarget = [
    'EformInput',
    'EformNumber',
    'EformSwitch',
    'EformTextArea',
    'EformDatePicker',
    'EformStaticList',
    'EformDynamicList',
    'SelectFile',
    'SelectFolder',
    'EformMemberSelect',
    'EformHidden',
  ].includes(properties?.['x-component']);

  const noHover =
    ['inBizTableActions', 'inBizTableIndex'].includes(dataIndex) ||
    !current ||
    properties?.['x-component'] === 'EformHidden';

  var realSchema = useMemo(() => {
    return properties
      ? {
        ...schema.schema,
        properties: {
          [current]: {
            ...properties,
            title: {
              status: false,
            },
            'x-component-props': {
              ...properties['x-component-props'],
              componentIsInline: true,
              className: properties['x-component-props'].className + ' inline-edit',
              inlineValue: ['SelectFile', 'SelectFolder'].includes(properties?.['x-component'])
                ? resetProps.record[`${dataIndex}@desc`] ??
                resetProps.record[`${dataIndex}$raw`] ??
                resetProps.record[dataIndex]
                : undefined,
              showMode:
                properties?.['x-component'] === 'EformStaticList'
                  ? 2
                  : properties['x-component-props'].showMode,
            },
            // 'x-value': getInitValue(),
          },
        },
      }
      : undefined;
  }, [inlineEditIndex]);


  var isCurrent =
    inlineEditIndex[0] === _id &&
    (inlineEditIndex[1] === dataIndex || inlineEditIndex[1] === '$$all') &&
    current &&
    inlineEdit;

  const clickHandle = () => {
    if (isTarget) {
      changeEditCell(_id, dataIndex, tdRef);
    } else {
      dispatch?.({
        ...editPage,
        data: resetProps.record,
      });
    }
  };

  useEffect(() => {
    if (formRef.current) {
      changeBeforeForm(formRef.current, inlineEditIndex[1] === '$$all', tdRef);
    }
    if (!(isCurrent && isTarget)) {
      notRenderRef.current = false;
    }
  }, [inlineEditIndex]);

  const getForm = (form) => {
    formRef.current = form;

    form?.addEffects('validateFailed', () => {
      onFieldValidateEnd('*', (field) => {
        // 新增的时候首次校验
        if (resetProps.record[dataIndex] === undefined) {
          $isError(!!field.errors.length);
        }
      });
    });
  };

  const getRawValue = (data) => {
    const allKeys = Object.keys(data ?? {});
    const result = Object.entries(data ?? {}).reduce((prev, [key, value]) => {
      if (key.indexOf('$raw') >= 0) {
        return prev;
      } else if (allKeys.includes(`${key}$raw`) && data[`${key}$raw`]) {
        prev[key] = data[`${key}$raw`];
      } else {
        prev[key] = value;
      }
      return prev;
    }, {});
    return result;
  };

  var content = useMemo(() => {
    const _cache =
      resetProps?.dataSetCache?.tranformValue(
        resetProps?.dataSetCache.getCacheData({
          ...resetProps.record,
          id: _id,
        }),
      ) ?? {};

    _cache['masterDatas'] = resetProps?.dataSetCache?.tranformValue(_cache['masterDatas']);
    const queryData = resetProps?.dataSetCache?.tranformValue({
      ...resetProps.record,
      id: _id,
    });
    if (queryData?.['masterDatas']) {
      queryData['masterDatas'] = resetProps?.dataSetCache?.tranformValue(queryData['masterDatas']);
    }
    let newChildren = children;
    if (children[1] && typeof children[1] === 'string') {
      newChildren =  [, multilingualFormat(children[1])]
    }
    let newRealSchema = null;
    if (isCurrent && isTarget) {
      newRealSchema = eventsRef.current?.onBeforeRenderComponent?.(realSchema, resetProps?.record, rowIndex, dataIndex, schema?.schema?.properties) ?? realSchema;
      newChildren = eventsRef.current?.onColumnsFormat?.(children?.[1], resetProps.record, rowIndex, dataIndex) || newChildren;
    }

    //@ts-ignore
    return isCurrent && isTarget && newRealSchema ? (
      <div
        className="subtable-inline-form"
        style={{
          paddingBottom:
            properties?.['x-component'] === 'EformTextArea' &&
              properties?.['x-component-props']?.showCount
              ? '16px'
              : 0,
        }}
        onKeyDown={e => {
          if (e.key.toLowerCase() == 'enter') {
            e.preventDefault()
          }
        }}
      >
        <RenderSimple
          schema={newRealSchema}
          id={schema.routeId}
          globalSDK={inbiz!.getGlobalSDK?.()}
          form={schema.form}
          getForm={getForm}
          onInit={(sdk) => onInit(current, sdk, rowIndex, dataIndex)}
          queryData={isCurrent && isTarget ? queryData : {}}
          cacheData={isCurrent && isTarget ? getRawValue(_cache) : {}}
          // initValue={initValue}
          ref={(r) => {
            r?.page.on('destroy', () => {
              const record = resetProps.dataSetCache.getCacheData(resetProps.record) || {};
              emit?.('onEditEnd', dataIndex, record[dataIndex], rowIndex);
            });
            return getPageRef(r, dataIndex);
          }}
        />
      </div>
    ) : noHover ? (
      newChildren
    ) : (
      <div className={`subtable-inline`}>
        <span>{newChildren}</span>
        {/* 如果readOnly为true,则inlineEdit为false */}
        {inlineEdit && (!readOnly) &&viewMode!='look'&& (
          <span className={`subtable-inline-icon`} onClick={clickHandle}>
            <InbizIcon type="icon-bianji1" style={{ color: 'var(--inbiz-color-primary)' }} />

          </span>
        )}
      </div>
    );
  }, [inlineEditIndex]);

  const isCurrentCell =
    inlineEditIndex[1] === dataIndex &&
    inlineEditIndex[0] === _id &&
    inlineEditIndex[0] &&
    isTarget;

  const addCell =
    inlineEditIndex[1] === '$$all' &&
    tdRef.current?.classList.contains('edit-inline-active') &&
    inlineEditIndex[0] === _id &&
    isTarget;
  const floatCell = inlineEditIndex[1] === '$$all' && inlineEditIndex[0] === _id && isTarget;
  return (
    <td
      {...resetProps}
      className={cs(
        'edit-inline-td',
        {
          'edit-inline-active': isCurrentCell || addCell,
          'edit-inline-float': isCurrentCell || floatCell,
          'edit-inline-active-error': isError,
        },
        resetProps.className,
      )}
      title={multilingualFormat(resetProps.title)}
      ref={tdRef}
      onClick={() => {
        if (
          inlineEditIndex[1] === '$$all' &&
          !tdRef.current?.classList.contains('edit-inline-active') &&
          isTarget
        ) {
          document.querySelector('.edit-inline-active')?.classList.remove('edit-inline-active');
          tdRef.current?.classList.add('edit-inline-active');
        }

        tdClickHandle(_id, dataIndex, current);
      }}
    >
      {content}
    </td>
  );
};

export default EditCellComponent;
